const {
  wxLogin
} = require('../api/login')
const {
  getPhoneNumber
} = require('../api/getPhoneNumber')

const {
  to,
  openLoading,
  closeLoading,
} = getApp()
const {
  setToken,
  setUserType,
  setUserBaseInformation,
  clearAll
} = require('../utils/strorage')
Page({
  data: {
    infoIsChecked: false
  },
  onLoad() {
    if (wx.canIUse('hideHomeButton')) {
      wx.hideHomeButton()
    }
  },
  async handleLogin(phoneNumber) {
    const [err, data] = await to(wxLogin(phoneNumber))
    closeLoading()
    if (!err) {
      setToken(data.token)
      setUserType(data.userType)
      setUserBaseInformation(data)
      this.navigateBackPosition()
    } else {
      clearAll()
    }
  },

  async loadPhoneNumber(code) {
    openLoading()
    const [err, phoneNumber] = await to(getPhoneNumber({
      code
    }))

    if (!err) {
      this.handleLogin(phoneNumber)
    } else {
      closeLoading()
    }
  },

  handleAgreePrivacyAuthorization(event) {
   
  },

  onGetPhoneNumber(event) {
    if (event.detail.errMsg === 'getPhoneNumber:fail user deny') return;

    if (event.detail.code) {
      this.loadPhoneNumber(event.detail.code);
    } else {
    }
  },

  navigateBackPosition() {
    const routeData = this.options.fromRouteData;
    if (routeData) {
      const datas = JSON.parse(routeData);
      const fromRoute = datas.fromRoute || '';
      const options = datas.options || {};
      let items = ''
      if (Object.keys(options).length) {
        const arrays = Object.keys(options).map(item => `${item}=${options[item]}`);
        items = '?' + arrays.join('&')
      }
      wx.reLaunch({
        url: '/' + fromRoute + items,
      })
    } else {
      wx.reLaunch({
        url: '/tabbar/index/index',
      })
    }
  },

  onGoLoginInfo() {
    wx.navigateTo({
      url: '/login/login-info/login-info',
    })
  },

  onInfoChange() {
    this.setData({
      infoIsChecked: !this.data.infoIsChecked
    })
  }
})